<template>
    <div class="product">
        <van-nav-bar title="商品列表" left-text="返回" left-arrow @click-left="onClickLeft" />
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <div class="product" v-for="(item, index) in productList" :key="index"
                    @click="router.push({ path: `/detail/${item.id}` })">
                    <van-image height="150" width="100%" fit="fill" :src="item.picture"></van-image>
                    <div class="product-info">
                        <h4 class="product-name">{{ item.name }}</h4>
                        <p class="product-price">
                            <span class="price">￥{{ item.price }}</span>
                            <span>{{ item.stock }}件</span>
                        </p>
                    </div>
                </div>
            </van-list>
        </van-pull-refresh>
    </div>
</template>

<script setup>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getProductListService } from "@/apis/product";
import { showFailToast } from "vant";
const route = useRoute();
const router = useRouter();
const productList = ref([]);
const pagesize = ref(4);
const last_id = ref(11);
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const onClickLeft = () => {
    history.back();
};
const onLoad = async () => {
    if (refreshing.value) {
        productList.value = [];
        refreshing.value = false;
    }
    let params = {
        category_id: route.params.id * 1,
        pagesize: pagesize.value,
        last_id: last_id.value,
    };
    let res = await getProductListService(params);
    productList.value.push(...res.data);
    last_id.value -= pagesize.value;
    loading.value = false;
    if (productList.value.length <= 0) {
        showFailToast("列表为空");
    }
    if (res.data.length < pagesize.value) {
        finished.value = true;
    }
};
const onRefresh = () => {
    // 清空列表数据
    finished.value = false;
    pagesize.value = 4;
    last_id.value = 11;
    // 重新加载数据
    // 将 loading 设置为 true，表示处于加载状态
    loading.value = true;
    onLoad();
};
</script>
<style scoped>
.van-list {
    display: flex;
    flex-wrap: wrap;
    column-gap: 5px;
    row-gap: 10px;
    justify-content: center;
    padding-top: 10px;
}

.product-price {
    display: flex;
    justify-content: space-between;
}

.price {
    color: #ee0a24;
}

.van-list .product {
    flex: 0 0 calc(50% - 5px);
}
</style>
